package com.acme.clientserver;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * Bank application remote client.
 * 
 */
public class BankClient {
	private static final String SERVER_HOST = "localhost";
	private static final int SERVER_PORT = 2013;

	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	BankClient() {
	}

	void run() {
		try {
			// 1. creating a socket to connect to the server
			requestSocket = new Socket(SERVER_HOST, SERVER_PORT);
			System.out.println("[CLIENT] Connected to "
					+ requestSocket.getRemoteSocketAddress() + " in port "
					+ requestSocket.getPort() + ". ");
			// 2. get Input and Output streams
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			// 3: Communicating with the server
			try (Scanner keyb = new Scanner(System.in)) {
				do {
					try {
						System.out.print("client> ");
						String command = keyb.nextLine();
						sendMessage(command);
						message = (String) in.readObject();
						System.out.println("server> " + message.trim());
					} catch (ClassNotFoundException classNot) {
						System.err
								.println("[ERROR] Data received in unknown format.");
					}
				} while (!message.equals("bye"));
			}
		} catch (UnknownHostException unknownHost) {
			System.err
					.println("[ERROR] You are trying to connect to an unknown host!");
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			// 4: Closing connection
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	private void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void main(final String args[]) {
		BankClient client = new BankClient();
		client.run();
	}

}
